
import { getRouters} from '@/request'
import router, {constantRoutes, dynamicRoutes } from '@/router'
import {
    __dynamicImportComponent__
} from 'uni-simple-router'
const permission = {
    state: {
        // 权限列表
        routes: [],
        addRoutes: [],
        defaultRoutes: [],
        topbarRouters: [],
        sidebarRouters: [],
        tabbarList: [],
    },
    mutations: {
        setRoutes: (state, routes) => {
            state.addRoutes = routes
            state.routes = constantRoutes.concat(routes)
        },
        setDefaultRoutes: (state, routes) => {
            state.defaultRoutes = constantRoutes.concat(routes)
        },
        setTopbarRouters: (state, routes) => {
            state.topbarRouters = routes
        },
        setSidebarRoutes: (state, routes) => {
            state.sidebarRouters = routes
        },
        setTabbarList: (state, routes) => {
            state.tabbarList = routes
        }
    },
    actions: {
        // 生成路由
        GenerateRoutes({ commit }) {
            return new Promise(resolve => {
                // 向后端请求路由数据
                getRouters().then(res => {
                    res.data.forEach( route => {
                        if (route.meta.title && route.meta.title === "移动端管理") {
                            commit('setRoutes', res.data);
                            // for(var i = 0; i < 10; i++) {
                              
                            //     uni.setTabBarItem({
                            //         index: i,
                            //         visible: false,
                            //     })
                               
                            // }
                            
                            let tabbarList = [];
                            route.children.forEach((navbar, index) => {
                                console.log(navbar.meta.title, index)
                                const{ iconPath,selectedIconPath} = getIconPath(navbar.meta.title)
                                tabbarList.push({
                                    index: index,
                                    pagePath: "/" + navbar.component,
                                    text: navbar.meta.title,
                                    iconPath: iconPath,
                                    selectedIconPath: selectedIconPath
                                });
                                
                                // uni.setTabBarItem({
                                //     index: index,
                                //     pagePath: "/" + navbar.component,
                                //     text: navbar.meta.title,
                                //     iconPath: iconPath,
                                //     selectedIconPath: selectedIconPath,
                                //     visible: true,
                                // })
                            })
                            
                            // resolve(route)
                            commit('setTabbarList', tabbarList);
                            console.log(this.state.permission.tabbarList)
                            // console.log(tabbarList,"tabbarList");
                            resolve(tabbarList)
                            
                        }
                    })

                   
           
                    // console.log(router)
                    // const sdata = JSON.parse(JSON.stringify(res.data))
                    // const rdata = JSON.parse(JSON.stringify(res.data))
                    // const sidebarRoutes = filterAsyncRouter(sdata)
                    // const rewriteRoutes = filterAsyncRouter(rdata, false, true)
                    // const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
                    // rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
                    // router.addRoute({ path: '/about', component: __dynamicImportComponent__("@/pages/index/index.vue") });

                })
            })
        }
    }
}

function getIconPath(name) {
    let icon = {
        iconPath: '../../static/tabBar/数字看板2.png',
        selectedIconPath: '../../static/tabBar/数字看板.png',
    }
    if( name.includes('数字看板')) {
        icon.iconPath = '../../static/tabBar/数字看板2.png';
        icon.selectedIconPath = '../../static/tabBar/数字看板.png'
    } else if (name.includes('预警处理')) {
        icon.iconPath = '../../static/tabBar/预警处理2.png';
        icon.selectedIconPath = '../../static/tabBar/预警处理.png'
    } else if (name.includes('监测上报')) {
        icon.iconPath = '../../static/tabBar/监测上报2.png';
        icon.selectedIconPath = '../../static/tabBar/监测上报.png'
    } else if (name.includes('运维记录')) {
        icon.iconPath = '../../static/tabBar/运维记录2.png';
        icon.selectedIconPath = '../../static/tabBar/运维记录.png'
    } else if (name.includes('我的')) {
        icon.iconPath = '../../static/tabBar/我的2.png';
        icon.selectedIconPath = '../../static/tabBar/我的.png'
    }
    return icon;
 }
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
    return asyncRouterMap.filter(route => {
        if (type && route.children) {
            route.children = filterChildren(route.children)
        }
        if (route.component) {
            // Layout ParentView 组件特殊处理
          
            route.component = loadView(route.component)
            
        }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children, route, type)
        } else {
            delete route['children']
            delete route['redirect']
        }
        return true
    })
}

function filterChildren(childrenMap, lastRouter = false) {
    var children = []
    childrenMap.forEach((el, index) => {
        if (el.children && el.children.length) {
            if (el.component === 'ParentView' && !lastRouter) {
                el.children.forEach(c => {
                    c.path = el.path + '/' + c.path
                    if (c.children && c.children.length) {
                        children = children.concat(filterChildren(c.children, c))
                        return
                    }
                    children.push(c)
                })
                return
            }
        }
        if (lastRouter) {
            el.path = lastRouter.path + '/' + el.path
        }
        children = children.concat(el)
    })
    return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
    const res = []
    routes.forEach(route => {
        if (route.permissions) {
            if (auth.hasPermiOr(route.permissions)) {
                res.push(route)
            }
        } else if (route.roles) {
            if (auth.hasRoleOr(route.roles)) {
                res.push(route)
            }
        }
    })
    return res
}

export const loadView = (view) => {
    if (process.env.NODE_ENV === 'development') {
        return (resolve) => require([`@${view}`], resolve)
    } else {
        // 使用 import 实现生产环境的路由懒加载
        return () => import(`@${view}`)
    }
}

export default permission